package divestoclimb.checklist;

import divestoclimb.checklist.data.Category;
import divestoclimb.checklist.storage.DbAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class CategoryName extends Activity implements Button.OnClickListener {
	
	private DbAdapter mDbHelper;
	private String mSavedText;
	private EditText mEditText;
	private Long mId;
	private Category mCategory;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.rename_dialog);
		mDbHelper = new DbAdapter(this);
		mDbHelper.open();

		Bundle params = icicle != null? icicle: getIntent().getExtras();
		mId = params.getLong(DbAdapter.KEY_CATEGORY_ID);
		if(mId == 0L) {
			mId = null;
		}
		// Try to retrieve the text that was in the field before the activity was
		// stopped
		if(icicle != null) {
			mSavedText = icicle.getString(DbAdapter.KEY_CATEGORY_NAME);
		}
		
		mCategory = mDbHelper.fetchCategory(mId);

		mEditText = (EditText)findViewById(R.id.content);
		TextView prompt = (TextView)findViewById(R.id.prompt);
		prompt.setText(getResources().getString(R.string.name_prompt));

		// Set up our button listeners
		Button ok = (Button) findViewById(R.id.button_ok);
		ok.setOnClickListener(this);
		Button cancel = (Button) findViewById(R.id.button_cancel);
		cancel.setOnClickListener(this);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if(mId != null) {
			outState.putLong(DbAdapter.KEY_CATEGORY_ID, mId);
		}
		outState.putString(DbAdapter.KEY_CATEGORY_NAME, mEditText.getText().toString());
	}
	
	@Override
	protected void onResume() {
		super.onResume();

		if(mId != null) {
			mEditText.setText(mCategory.getName());
		}
		if(mSavedText != null) {
			mEditText.setText(mSavedText);
		}
	}

	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.button_cancel:
			setResult(RESULT_CANCELED);
			finish();
			break;
		case R.id.button_ok:
			String name = mEditText.getText().toString();
			if(mId == null) {
				// Create a new Category with this as the name
				mCategory = new Category(name);
			} else {
				mCategory.setName(name);
			}
			if(mCategory.save(mDbHelper)) {
				Intent i = new Intent()
					.putExtra(DbAdapter.KEY_CATEGORY_ID, mCategory.getID());
				setResult(RESULT_OK, i);
				finish();
			} else {
				Toast.makeText(this, R.string.category_save_failed, Toast.LENGTH_LONG).show();
			}
		}
	}
}